<template>
  <div class="rulelist">
    <jc-button
      :btn-arr="['reload', bomCost('per:insertRole') && 'newy', 'remove']"
      :disab-arr="['copy']"
      @refresh="getUserList"
      @newly="addDialogVisible = true"
      @del="delectRole"
    />
    <div class="header">
      <div class="header-name">
        <search
          :options="selectData"
          :search-son="searchSon"
          :msg="tacitly"
          @seek="collect"
          @hand="searchMaterialList"
        />
        <el-button size="mini" type="primary" class="btn" @click="searchMaterialList">
          {{ $t('btn.search') }}
        </el-button>
        <filtration
          :ftype="ftype"
          :msg="tacitly"
          :select-data="selectData"
          :table-header="tableHeader1"
          :detail-header="tableHeader"
          @seachData="searchMaterialList"
        />
      </div>
    </div>
    <div class="table-content">
      <jc-table
        v-loading="loading"
        :table-data="tableData"
        :table-header="tableHeader"
        sortable
        table-selection
        @selectionChange="selectionData"
      >
        <template v-slot:btnSlot="col">
          <el-button
            type="primary"
            size="mini"
            @click="authority(col.scope.row.fpkId)"
          >
            {{ $t('market.authority') }}<!--权限管理-->
          </el-button>
        </template>
      </jc-table>
    </div>
    <div class="footer">
      <jc-pagination
        v-show="total > 0"
        :total="total"
        :page.sync="pageNum"
        :limit.sync="size"
        @pagination="getUserList"
      />
    </div>
    <!--权限管理-->
    <el-dialog
      v-dialogDrag
      title="权限管理"
      class="dialog2"
      :visible.sync="centerDialogVisible"
      width="50%"
      top="5vh"
      center
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-tree
        ref="menuTree"
        :data="treeData"
        show-checkbox
        node-key="menuId"
        :default-checked-keys="treeTrue"
        :default-expanded-keys="expandMenu"
        :props="defaultProps"
        highlight-current
        :filter-node-method="filterNode"
        :check-strictly="false"
      />
      <div slot="footer" class="dialog-footer">
        <el-checkbox
          v-model="checked"
          class="checkAll"
          @change="checkAll(checked)"
        ><!--          全选-->
          {{ $t('market.allCheck') }}
        </el-checkbox>
        <el-button size="medium" @click="handleClose">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" size="medium" @click="roleSubmit">
          {{ $t('btn.sub') }}
        </el-button>
      </div>
    </el-dialog>
    <!--新增角色-->
    <el-dialog
      v-dialogDrag
      :title="$t('market.roleAdd')"
      :visible.sync="addDialogVisible"
      width="500px"
      center
      :close-on-click-modal="false"
    >
      <el-form
        ref="ruleForm"
        :model="addRole"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item :label="$t('market.roleName')" prop="name">
          <el-input v-model.trim="addRole.name" size="mini" />
        </el-form-item>
        <el-form-item :label="$t('market.roleDesc')" prop="depict">
          <el-input v-model.trim="addRole.depict" size="mini" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addHandleClose">{{ $t('btn.cancel') }}</el-button>
        <el-button type="primary" @click="addRoleSubmit">{{ $t('btn.sub') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryTJxRoleList
} from '@/api/basicManagement/userslist'
import search from '@/components/Search/index'
import searData from '@/components/Search/mixin'
import filtration from '@/components/filtration'
import { deleteRole, inserRole, updateRoleMeun } from '@/api/userAdmin/roleList'
import {
  queryTreeMenu
} from '@/api/basicManagement/menu'
import jcButton from '@/components/Button'
export default {
  components: {
    search,
    jcButton,
    filtration
  },
  mixins: [searData],
  data() {
    return {
      checked: false, // 全选
      isIndeterminate: true,
      addDialogVisible: false, // 新增角色
      centerDialogVisible: false, // 权限管理
      ftype: 27,
      fbillNo: 'fname',
      total: 0, // 总条目
      pageNum: 1, // 当前页
      size: 200, // 每页显示多少条数据
      tableData: [], // 列表数据
      // 表头数据
      tableHeader: [
        { label: this.$t('market.roleName'), prop: 'name' },
        { label: this.$t('market.rolexplain'), prop: 'depict' },
        { label: this.$t('market.forbidStatu'), prop: 'isdisable' },
        { label: this.$t('market.createDate'), prop: 'createDate' },
        { label: this.$t('market.handle'), type: 'btn', width: '180' }
      ],
      tableHeader1: [],
      treeData: [],
      defaultProps: {
        children: 'childList',
        label: 'menuName'
      },
      treeTrue: [], // 选中的数据
      expandMenu: [], // 默认展开
      treeSubData: {
        roleId: '', // 角色ID
        children: []
      }, // 权限管理提交数据
      addRole: {
        name: '',
        depict: ''
      },
      treeTrue1: [],
      treeSubData1: [],
      rules: {
        // 验证不能为空
        name: [{ required: true, message: '请输入名称', trigger: 'change' }],
        depict: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getUserList()
    this.tableHeader1 = this.tableHeader
  },
  methods: {
    // 角色列表
    async getUserList() {
      this.loading = true
      const DATA = {
        formId: 'sec_role',
        pageNum: this.pageNum,
        pageSize: this.size,
        search: this.searCollData
      }
      const { data: res } = await queryTJxRoleList(DATA)
      this.tableData = res.array
      this.total = res.total
      this.loading = false
    },
    // 搜索物料
    searchMaterialList(ev) {
      this.pageNum = 1
      if (ev && ev.fname) {
        this.searchSon = ev.detail
        this.customHandle(ev)
        this.getUserList(ev.detail)
      } else {
        this.getUserList()
      }
    },
    // 自定义列表
    customHandle(ev) {
      this.tableHeaders = []
      if (ev.header) {
        ev.header.forEach(item => {
          this.tableHeader1.forEach(res => {
            if (res.label === item) {
              this.tableHeaders.push(res)
            }
          })
        })
        this.tableHeader = this.tableHeaders
      } else if (ev.fname === '缺省方案') {
        this.tableHeader = this.oldTabHeader
      } else {
        this.tableHeader = this.tableHeader1
      }
    },
    // 权限管理-详情
    authority(fpkid) {
      this.treeTrue = []
      this.treeSubData.children = []
      this.treeSubData.roleId = fpkid
      this.centerDialogVisible = true
      queryTreeMenu({ roleId: fpkid }).then(res => {
        this.treeData = res.data
        res.data.filter(item => {
          this.expandMenu.push(item.menuId)
          this.callCheck(item)
          return this.treeTrue
        })
      })
    },
    callCheck(item) {
      if (item.flg) { // 一级
        this.treeTrue.push(item.menuId)
        this.treeSubData.children.push({ menuId: item.menuId })
      }
      if (item.childList && item.childList.length > 0) {
        item.childList.forEach(ite => { // 二级
          this.callCheck(ite)
        })
      }
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 修改权限-提交
    roleSubmit() {
      const children = this.$refs.menuTree.getCheckedKeys()
      this.treeSubData.children = []
      children.forEach(res => {
        this.treeSubData.children.push({
          menuId: res
        })
      })
      const DATA = { ...this.treeSubData }
      updateRoleMeun(DATA).then(res => {
        if (res.code === 0) {
          this.$message({ showClose: true, message: res.message, type: 'success' })
          this.centerDialogVisible = false
          this.getUserList()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 修改权限 -- 全选(组件el-tree, setCheckedKeys方法实现)
    checkAll(ev) {
      this.treeData.map(item => {
        this.callCheck1(item)
      })
      if (!ev) {
        this.checked = false
        this.treeTrue = []
        this.$refs.menuTree.setCheckedKeys(this.treeTrue)
      } else {
        this.checked = true
        this.$refs.menuTree.setCheckedKeys(this.treeTrue)
      }
    },
    callCheck1(item) {
      this.treeTrue.push(item.menuId)
      this.treeSubData.children.push({ menuId: item.menuId })
      if (item.childList && item.childList.length > 0) {
        item.childList.filter(ite => {
          this.treeTrue.push(ite.menuId)
          this.treeSubData.children.push({ menuId: ite.menuId })
          this.callCheck1(ite)
        })
      }
    },
    // 新增角色提交
    addRoleSubmit() {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) {
          return
        }
        const DATA = { ...this.addRole }
        inserRole(DATA).then(res => {
          if (res.code === 0) {
            this.addRole = {
              name: '',
              depict: ''
            }
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.addDialogVisible = false
            this.getUserList()
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 多选
    selectionData(val) {
      this.delArr = []
      val.forEach(res => {
        this.delArr.push(res.fpkId)
      })
    },
    // 删除角色
    delectRole() {
      this.$confirm('确定要删除该角色么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole({ Numbers: this.delArr }).then(res => {
          if (res.code === 0) {
            this.innerHTM = ''
            res.data.forEach(res => {
              this.innerHTM += '<div>' + res + '</div>'
            })
            this.$notify.warning({
              title: '提示',
              message: this.innerHTM,
              duration: 3000, offset: 50,
              dangerouslyUseHTMLString: true
            })
            this.getUserList()
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      })
    },
    // 新增角色 关闭前回调
    addHandleClose() {
      this.addRole = {}
      this.addDialogVisible = false
    },
    // 权限管理 关闭前回调
    handleClose() {
      this.treeTrue = []
      this.centerDialogVisible = false
    }
  }
}
</script>

<style scoped lang="scss">
.rulelist {
  @include listBom;
  .dialog2::v-deep .el-dialog__body {
    max-height: 500px;
    overflow: auto;
    .el-tree {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: flex-start;
    }
  }
  .header {
    position: relative;
    .header-name {
      width: 100%;
    }
    .btn {
      transform: translateY(18%);
      margin-left: 450px !important;
    }
  }
  .checkAll {
    margin-right: 10px;
  }
}
</style>
